#include <stdio.h>
#include <stdlib.h>
#include "LinkList.h"

//保存尾部结点 避免每次插入一个新结点时 每次都要遍历到末尾
static struct LinkNode *pRear = NULL;

//初始化链表
struct LinkNode *newLinkList()
{
	//创建头结点
	struct LinkNode *header = malloc(sizeof(struct LinkNode));
	header->data = -1;
	header->next = NULL;
	pRear = header;

	return header;
}

//在值val的后面插入一个新的数据newval 拿到头相当于拿到整个链表
void insertLinkListByAfterValue(struct LinkNode *header, int value, int newValue)
{
	if(NULL == header)
	{
		return;
	}

	//两个辅助指针变量
	struct LinkNode *pPrev = header;
	struct LinkNode *pCurrent = pPrev->next;

	while(pCurrent != NULL)
	{
		if(pCurrent->data == value)
		{
			break;
		}

		pPrev = pCurrent;
		pCurrent = pCurrent->next;
	}

	//如果pCurrent为NULL 说明链表中不存在值为value的结点
	//如果没找到,就不插入,加入这段代码
	//如果没找到,就插入到末尾,注释掉这段代码 推荐
	//两种可以由用户选择
#if 0
	if(NULL == pCurrent)
	{
		return;
	}
#endif

	//先创建新结点
	struct LinkNode *newNode = malloc(sizeof(struct LinkNode));
	newNode->data = newValue;
	newNode->next = NULL;

	//新结点插入到链表中
	newNode->next = pCurrent;
	pPrev->next = newNode;
}

//删除值为val的结点
void deleteLinkListNodeByValue(struct LinkNode *header, int deleteValue)
{
	if(NULL == header)
	{
		return ;	
	}

	//两个辅助指针变量
	struct LinkNode *pCurrent = header->next;
	struct LinkNode *pPrev = header;

	while(pCurrent != NULL)
	{
		if(pCurrent->data == deleteValue)
		{
			break;
		}

		pPrev = pCurrent;
		pCurrent = pCurrent->next;
	}

	if(NULL == pCurrent)
	{
		return ;
	}

	pPrev->next = pCurrent->next;
	free(pCurrent);
	pCurrent = NULL;
}

//遍历
void foreachLinkList(struct LinkNode *header)
{
	if(NULL == header)
	{
		return ;
	}

	//辅助指针变量
	struct LinkNode *pCurrent = header->next;
	while(pCurrent != NULL)
	{
		printf("%d ", pCurrent->data);
		pCurrent = pCurrent->next;
	}

	printf("\n");
}

//销毁
void destroyLinkList(struct LinkNode *header)
{
	if(NULL == header)
	{
		return;
	}

	clearLinkList(header);
	free(header);
	header = NULL;
}

//清空
void clearLinkList(struct LinkNode *header)
{
	if(NULL == header)
	{
		return;
	}
	
	//除头部结点,其他结点释放掉
	
	//需要一个辅助指针变量
	struct LinkNode *pCurrent = header->next;
	while(pCurrent != NULL)
	{
		//先保存当前结点的下一个结点
		struct LinkNode *pNext = pCurrent->next;
		//释放当前结点的内存
		free(pCurrent);
		//让pCurrent指向下一个结点
		pCurrent = pNext;
	}

	header->next = NULL;
}

//链表逆序
void reverseLinkList(struct LinkNode *header)
{
	if(NULL == header)
	{
		return;
	}

	struct LinkNode *pPrev = NULL;
	struct LinkNode *pCurrent = header->next;
	struct LinkNode *pNext = NULL;

	while(pCurrent != NULL)
	{
		pNext = pCurrent->next;
		pCurrent->next = pPrev;

		pPrev = pCurrent;
		pCurrent = pNext;
	}

	header->next = pPrev;
}
